package ru.urfc.portal.model.admins;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import ru.urfc.portal.exceptions.UserGetItemException;
import ru.urfc.portal.model.Client;
import ru.urfc.portal.model.SysObject;
import ru.urfc.portal.ui.client.Constants;

@Table(name = "USER_TABLE")
@Entity
@XmlRootElement(name = Constants.USER)
public class User extends SysObject {
	private Client client; 
	public String firstName;
	public String lastName;
	public String middleName;
	@Column(unique = true)
	private String email;
	public String phone;
	@ManyToOne(fetch = FetchType.EAGER)
	private UserRole role;
	@ManyToOne(fetch = FetchType.EAGER)
	private UserState state;
	
	public User() {
	}

	public User(Client client, String firstName, String middleName,
			String lastName, String email, String phone, UserRole role,
			UserState state) {
		this(null, client, firstName, middleName, lastName, email, phone, role, state);
	}
	
	public User(Long id, Client client, String firstName, String middleName,
			String lastName, String email, String phone, UserRole role,
			UserState state) {
		super(id);
		this.client = client;
		this.firstName = firstName;
		this.middleName = middleName;
		this.lastName = lastName;
		this.email = email;
		this.phone = phone;
		this.role = role;
		this.state = state;
	}

	public User(Client client, UserCreate user) {
		this.client = client;
		this.firstName = user.getFirstName();
		this.lastName = user.getLastName();
		this.middleName = user.getMiddleName();
		this.email = user.getEmail();
	}

	public User(String email) {
		this.email = email;
	}

	@XmlTransient
	public Client getClient() {
		return client;
	}

	public void setClient(Client client) {
		this.client = client;
	}

	public User check(Long clientId) {
		if (!getClient().getId().equals(clientId)) {
			throw new UserGetItemException(User.class);
		}
		return this;
	}

	public UserRole getRole() {
		return role;
	}

	public void setRole(UserRole role) {
		this.role = role;
	}

	public UserState getState() {
		return state;
	}

	public void setState(UserState state) {
		this.state = state;
	}
	
	@XmlElement
	public String getEmail() {
		return email;
	}

	public User update(UserSelfUpdate userSelfUpdate) {
		this.firstName = userSelfUpdate.getFirstName();
		this.middleName = userSelfUpdate.getMiddleName();
		this.lastName = userSelfUpdate.getLastName();
		this.phone = userSelfUpdate.getPhone();
		return this;
	}

}
